package com.qttaudio.example;

import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.qttaudio.example.config.Config;
import com.qttaudio.example.utils.AudioDataObserverImpl;
import com.qttaudio.ios.demo.R;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RecordFileActivity extends BaseAvtivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.lv_singleChoice)
    ListView mSingleListView;
    @BindView(R.id.togglePlay)
    ToggleButton togglePlay;
    @BindView(R.id.buttonStop)
    Button buttonStop;
    @BindView(R.id.buttonDel)
    Button buttonDel;
    @BindView(R.id.iv_back)
    ImageView ivBack;

    private ArrayList<String> mTestData;
    private ArrayList<String> mFilePath;
    private MediaPlayer mediaPlayer = null;
    private boolean isPlaying = false;
    ArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_file);
        ButterKnife.bind(this);
        mTestData = new ArrayList<>();
        mFilePath = new ArrayList<>();

        adapter = new ArrayAdapter<String>(this, R.layout.item_lv_single_choice, initData());
        mSingleListView.setAdapter(adapter);

        mSingleListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);


        mSingleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                int checkedItemPosition = mSingleListView.getCheckedItemPosition();

            }
        });

        togglePlay.setOnCheckedChangeListener(this);

    }

    private ArrayList<String> initData() {
        mTestData.clear();
        mFilePath.clear();
        String path = Config.record_dir;
        AudioDataObserverImpl.mkDirectory(path);

        File dir = new File(path);
        File[] filelist = dir.listFiles();
        for (File file : filelist) {
            mTestData.add(file.getName());
            mFilePath.add(file.getAbsolutePath());
        }

        return mTestData;
    }

    private void stop() {
        if (!isPlaying)
            return;
        isPlaying = false;
        togglePlay.setChecked(false);
        mSingleListView.setEnabled(true);
        buttonDel.setEnabled(true);
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stop();
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (!compoundButton.isPressed()) return;

        if (b) {
            if (mSingleListView.getCheckedItemPosition() < 0) {
                Toast.makeText(RecordFileActivity.this, "请选择一个文件", Toast.LENGTH_SHORT).show();
                togglePlay.setChecked(false);
                return;
            }
            if (!isPlaying) {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setLooping(true);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(mFilePath.get(mSingleListView.getCheckedItemPosition()));
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    isPlaying = true;
                    mSingleListView.setEnabled(false);
                    buttonDel.setEnabled(false);
                } catch (IOException e) {
                    e.printStackTrace();
                    compoundButton.setChecked(false);
                    Toast.makeText(RecordFileActivity.this, "播放失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                mediaPlayer.start();
            }
        } else
            mediaPlayer.pause();
    }

    @OnClick(R.id.buttonStop)
    public void onButtonStopClicked() {
        stop();
    }

    @OnClick(R.id.buttonDel)
    public void onButtonDelClicked() {
        showDelDialog();

    }


    private void showDelDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确定删除此文件吗？")
                .setCancelable(false)
                .setNegativeButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                dialog.cancel();
                                File file = new File(mFilePath.get(mSingleListView.getCheckedItemPosition()));
                                file.delete();
                                mSingleListView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        adapter = new ArrayAdapter<String>(RecordFileActivity.this, R.layout.item_lv_single_choice, initData());
                                        mSingleListView.setAdapter(adapter);
                                    }
                                });
                            }
                        })
                .setPositiveButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        stop();
        finish();
    }
}
